import React,{ Fragment,useEffect,useState,FC} from "react"
import {  Button,Table,Modal,message,Form,Input } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import * as api from "@/api/category"
import {addCategoryApi,updateCategoryApi} from "@/api/category"
import "./category.css"
// 引入Modal对话框
import MyModal from "@/modal对话框封装/myModal";
import { FormInstance } from "rc-field-form"
import { createFromIconfontCN } from '@ant-design/icons';
// 自定义 font 图标
const MyIcon = createFromIconfontCN({
    scriptUrl: '//at.alicdn.com/t/c/font_3605787_y8iuccq5oc.js', // 在 iconfont.cn 上生成
});
interface DataType {
  categoryImgurl:string;
  category_id: string;
  categoryName: string;
  createTime: string;
  creator: string;
  updateTime: string;
  updator: string;
}
const ProductCategory = () => {
  //声明一个要记录要被删除的类目id状态
  let [delId, setDelId] = useState<string | undefined>()
  // 记录当前的modal选择器中category——id
  let [currentCategoryId,setCurrentCategoryId] = useState<string | undefined>("")
  //声明Form实例
  let [modalForm] = Form.useForm()
  //控制modal弹框的标题
  let [modalTitle, setModalTitle] = useState('')
  //控制Modal显示和隐藏
  let [modalOpen, setModalOpen] = useState<boolean>(false)
  // 存放表格数据
  let [categorydata,setCategory] = useState<any>()
  //控制普通modal显示和隐藏
  let [isModalOpen, setIsModalOpen] = useState<boolean>()
  //标记点击了modal的确认按钮后是编辑还是增加 add/edit
  let [actionType,setActionType] = useState("add")
  //声明编辑数据的方法
  let edit = async (record: DataType) => {
    // console.log(record);
      //打开模态框
      setModalOpen(true)
      //更改modal的标题
      setModalTitle('修改类目')
      // 浅拷贝record
      let newRecord = {...record}
      // console.log(newRecord); 
      // 设置回显数据
      modalForm.setFieldsValue(newRecord)
      //  记录当前的category_id
      setCurrentCategoryId(newRecord.category_id)
  }
  // 声明删除数据的方法
  let del=async(record:any)=>{
    // console.log(record)
    setDelId(record.category_id)
    //弹窗
    setIsModalOpen(true)
  } 
   //声明列数据
  const columns: ColumnsType<DataType> = [
    {
      title: '类目图片',
      dataIndex: 'categoryImgurl',
      align: 'center',
      render(row,record){ 
        return(
          <img src={row} width={50}/>
        )
      }
    },
    {
      title: '类目id',
      dataIndex: 'category_id',
      align: 'center',
    },
    {
      title: '项目名称',
      dataIndex: 'categoryName',
      align: 'center',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: 'center',
    },
    {
      title: '创建人',
      dataIndex: 'creator',
      align: 'center',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      align: 'center',
    },
    {
      title: '更新人',
      dataIndex: 'updator',
      align: 'center',
    },
    {
      title: '操作',
      align: 'center',
      render(record){
        // console.log(record);//行的数据 setIsModalOpen(true); 
        return(
          <div className="action_button">
            <Button type="primary" icon={<MyIcon type="icon-chakan"/>} style={{background:'green'}}>查看</Button>
            <Button type="primary" icon={<MyIcon type="icon-bianjishuru-xianxing"/>} onClick={
              ()=>{
                edit(record)
                setActionType('edit')
              }
            }>编辑</Button>
            <Button type="primary" danger icon={<MyIcon type="icon-shanchu"/>} onClick={
                () => {
                    del(record)
                }
            }>删除</Button>
          </div>
        )
      }
    }
  ]; 
  // 获取类目列表,渲染表格数据
  let getCategoryList=()=>{
    // 发起请求获取数据
    api.getCategoryApi()
    .then((res:any)=>{
        // console.log(res);  
        if(res.data.state)  {
          //映射处理之后的数据,加了key字段
          //因为dataSource中必须要定义key,所以使用map进行处理,增加一个key
          let dataSource = res.data.data.map((item:any)=>{
            return{
              key:item._id,
              ...item,
              updator: item.updator ?? '暂无',
              updateTime: item.updateTime ?? '暂无修改'
            }
          })
          setCategory([...dataSource])
        }  
    })
  }
  //发起请求,获取列表数据
    useEffect(()=>{
     //dom挂载之后,请求数据
    getCategoryList()
  },[])

    //封装的modal的确定按钮,并且表单校验通过的回调
    let handleOnok = async (form: FormInstance | undefined) => {
      // 当前是增加操作
      if(actionType==='add'){
        //获取modal表单中的数据
        let formData = form?.getFieldsValue();
        // console.log(formData)
        // 添加数据
        try{
          let res = await addCategoryApi(formData.categoryName,formData.imageUrl)
          // console.log(res)
          setModalOpen(false)
          if(res.data.state){
            message.success('添加成功')
            // 添加成功，更新数据
          getCategoryList()
        }
        }catch(e){
          console.log(e);      
        }   
      }else if(actionType==='edit'){
        let formData = form?.getFieldsValue();
        // console.log(formData);
        try{
            let res = await updateCategoryApi(formData.categoryName,currentCategoryId)
            // console.log(res)
            setModalOpen(false)
            if(res.data.state){
              message.success('修改成功')
              // 修改成功，更新数据
              getCategoryList()
          }
        }catch(e){
          console.log(e);      
        }  
      }
  }
  //封装的modal的取消按钮的回调
  let handleOncancel = (form: FormInstance | undefined) => {
      console.log(form)
      setModalOpen(false)
      //清除Form实例上的data数据
      form?.resetFields()
      message.warning('已取消操作')
  }
  // console.log(selectValue)
    //普通对话框的确定按钮
    let handleOk = async () => {    
        // 发起删除请求
        api.delCategoryApi(delId)
        .then((res:any)=>{
          // console.log(res);
          if(res.data.state){
            message.open({
              type: 'success',
              content: '删除成功',
            }); 
            // 删除成功，更新列表
            getCategoryList()
            setIsModalOpen(false)
          }
        }) 
    }
    //普通对话框的取消按钮
    let handleCancel = () => {
        setIsModalOpen(false)
        message.warning('已取消删除')
    }
    return(
        <Fragment>
           {/* 确认对话框 */}
            <Modal title="删除提示" okText='确认删除' centered cancelText='取消删除' open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <p>是否要删除这条数据?</p>
            </Modal>
            {/* 对话框 */}
            <MyModal formInstance={modalForm} title={modalTitle} open={modalOpen} onOk={handleOnok} onCancel={handleOncancel}>
                <Form.Item label="项目名称" name="categoryName" rules={[{ required: true, message: '请输入商品名称' }]}>
                    <Input/>
                </Form.Item>
            </MyModal>
            <Button type="primary" onClick={() => {
                setModalOpen(true)
                setModalTitle('添加类目')
                setActionType('add')
            }}>点击添加</Button>
            <Table
            columns={columns}
            dataSource={categorydata}
            bordered
            scroll={{  y: 500 }}
            />
        </Fragment>
      )
};

export default ProductCategory;